package com.yupi.project.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

public class FoutConsumer {
  private static final String EXCHANGE_NAME = "logs";

  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();

    // 创建第一个通道
    Channel channel = connection.createChannel();

    // 声明交换机
    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

    // 声明队列
    String queueName = "queue1";
    channel.queueDeclare(queueName, true, false, false, null);

    // 绑定队列到交换机
    channel.queueBind(queueName, EXCHANGE_NAME, "");

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    DeliverCallback deliverCallback = (consumerTag, delivery) -> {
      String message = new String(delivery.getBody(), "UTF-8");
      System.out.println(" [x1] Received '" + message + "'");
    };
    channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });

    // 创建第二个通道
    Channel channel1 = connection.createChannel();

    // 声明第二个队列
    String queueName2 = "queue2";
    channel1.queueDeclare(queueName2, true, false, false, null);

    // 绑定第二个队列到交换机
    channel1.queueBind(queueName2, EXCHANGE_NAME, "");

    DeliverCallback deliverCallback2 = (consumerTag, delivery) -> {
      String message = new String(delivery.getBody(), "UTF-8");
      System.out.println(" [x2] Received '" + message + "'");
    };
    channel1.basicConsume(queueName2, true, deliverCallback2, consumerTag -> { });
  }
}